<?php
$menu = 1;

$type = '개설';
if($_GET['id']) {
    $type = "수정";
}
$title = "강의 ".$type; 

$g4_path = "../"; 
require_once ($g4_path.'common.php');
require_once ('./admin.head.php');
require_once ('./admin.lib.php');

$tpl = new Template_;
$tpl->template_dir = './tpl';
$tpl->compile_dir = './tpl/compile';
$tpl->assign('type', $type);

$perPage = 10;
$_datano = 0;
$_temp = $sqlWhere = $attachfile = $moviefile = NULL; 
$_isUseCate4 = TRUE; 
$_regcode = 'register';
$_attachFileAllow = array('hwp','doc','xls','docx','xlsx','ppt','txt','docs','pptx','zip','rar','alz','pdf','jpg','jpeg','png','gif'); 
$_bannerFileAllow = array('jpg','jpeg','png','gif'); 
$_movieFileAllow = array('asf','asx','mpg','mpeg','avi','mov','flv');
$_attachFileDir = '../data/courseAttach/';
$_movieFileDir = '../data/courseMovie/';
$_bannerFileDir = '../data/courseBanner/';
$daysArray = array('w_mon' => "월", 'w_tue' => "화", 'w_wed' => "수", 'w_thu' => "목", 'w_fri' => "금");
$weekArray = array();

if($_POST) { //등록,수정,삭제 시 처리
    $name = addslashes($_POST['name']) or alert("제목은 필수 항목입니다.");
    //$code = $_POST['code'];


    extract($_POST);
    
    $teacher = (int)$_POST['teacher']; 
    $bookcode = (int)$_POST['cate4']; 
    $year = (int)$_POST['year'];
    $month = (int)$_POST['month'];
    $starttime = (int)$_POST['starttime'];
    $perlimit = (int)$_POST['perlimit'];
    $level = (int)$_POST['level'];
    $price = (int)$_POST['price'];
    $contents = addslashes($_POST['contents']); 
    $check = $_POST['check'];
    
    $weekArray = split(',',$_POST['weekArray']); 
    if(sizeof($weekArray)==0 || !$year || !$month || !$starttime) {
        alert('시간 설정이 되지 않았습니다.');
    }
    $w_mon = in_array('월',$weekArray);
    $w_tue = in_array('화',$weekArray);
    $w_wed = in_array('수',$weekArray);
    $w_thu = in_array('목',$weekArray);
    $w_fri = in_array('금',$weekArray);
    $w_sat = in_array('토',$weekArray);
    $w_sun = in_array('일',$weekArray);

    $sql = "SET name = '$name', teacher = '$teacher', `year` = '$year', `month` = '$month', w_mon = '$w_mon', w_tue = '$w_tue', w_wed = '$w_wed', w_thu = '$w_thu', w_fri = '$w_fri', w_sat = '$w_sat', w_sun = '$w_sun', starttime = '$starttime', perlimit = '$perlimit', `level` = '$level', price = '$price', contents = '$contents', `check` = '$check', bookcode = '$bookcode'";
   
    switch($_POST['regcode']) {
        case 'modify': // 강의 수정
           $sql = "UPDATE course ".$sql;

           if(isset($_POST['attachfiledelete']) && $_POST['attachfiledelete'] == "on") {
                fileDelete($_POST['attachfile'], 'course', 'attachfile', $_POST['datano'], $_attachFileDir);
                $sql .= ", attachfile=''"; 
           }
           if(isset($_POST['bannerfiledelete']) && $_POST['bannerfiledelete'] == "on") {
                fileDelete($_POST['bannerfile'], 'course', 'bannerfile', $_POST['datano'], $_attachFileDir);
                $sql .= ", attachfile=''"; 
           }
           
           if(isset($_POST['moviefiledelete']) && $_POST['moviefiledelete'] == "on") {
                fileDelete($_POST['moviefile'], 'course', 'moviefile', $_POST['datano'], $_movieFileDir);
                $sql .= ", moviefile=''"; 
           }
           $sqlWhere = " WHERE no = '".$_POST['datano']."' ";
        break;
        case 'register': // 강의 추가
            /**** 카테고리 추가 ****/
            $_temp = sql_fetch("SELECT mb_id FROM g4_member WHERE `mb_no`= '$teacher'"); 
            $_tempquery = sql_fetch("SELECT bo_category_list as cmt FROM g4_board WHERE `bo_table` = 't_".$_temp['mb_id']."'");
            $_cateArray = explode("|", $_tempquery['cmt']);
            $_cateName = ereg_replace('\|','', $name); 
            if(!in_array($_cateName, $_cateArray)) {
                array_push($_cateArray, $_cateName); 
                $_str = implode("|", $_cateArray);
                $_makequery = "UPDATE g4_board SET `bo_category_list` = '$_str' WHERE `bo_table` = 't_".$_temp['mb_id']."'";
                sql_query($_makequery);
            }
            /**** 카테고리 추가 끝 ****/
            $sql = "INSERT INTO course ".$sql;
        break;
        case 'delete': // 강의 삭제
            /*** 카테고리 삭제 ***/
            $_temp = sql_fetch("SELECT mb_id FROM g4_member WHERE `mb_no`= '$teacher'"); 
            $_tempquery = sql_fetch("SELECT bo_category_list as cmt FROM g4_board WHERE `bo_table` = 't_".$_temp['mb_id']."'");
            $_cateArray = explode("|", $_tempquery['cmt']);
            if($key = array_search($name, $_cateArray)) {
                array_splice($_cateArray, $key, 1);
                $_str = implode("|", $_cateArray);
                $_makequery = "UPDATE g4_board SET `bo_category_list` = '$_str' WHERE `bo_table` = 't_".$_temp['mb_id']."'";
                sql_query($_makequery);
            }
            /*** 카테고리 삭제 끝 ****/
            if($_POST['attachfile']) {
                fileDelete($_POST['attachfile'], 'course', 'attachfile', $_POST['datano'], $_attachFileDir);
            }
            if($_POST['bannerfile']) {
                fileDelete($_POST['bannerfile'], 'course', 'bannerfile', $_POST['datano'], $_bannerFileDir);
            }
            if($_POST['moviefile']) {
                fileDelete($_POST['moviefile'], 'course', 'moviefile', $_POST['datano'], $_movieFileDir);
            }
            $sql = "DELETE FROM course WHERE no = '".$_POST['datano']."' LIMIT 1"; 
        break;
        default:
            alert('오류 : 잘못된 접근입니다.', './courseManage.php'); 
    }
    
    // 업로드 파일 처리
    if($_POST['regcode'] != 'delete' && isset($_FILES['attach']['name']) && $_FILES['attach']['error'] == 0) {
        if($_POST['attachfile']) {
            fileDelete($_POST['attachfile'], 'course', 'attachfile', $_POST['datano'], $_attachFileDir);
        }
        $attachfile = fileUpload('attach',$_attachFileDir, $_attachFileAllow); 
        $sql .= ", attachfile='".$attachfile."'"; 
    }
    if($_POST['regcode'] != 'delete' && isset($_FILES['banner']['name']) && $_FILES['banner']['error'] == 0) {
        if($_POST['bannerfile']) {
            fileDelete($_POST['bannerfile'], 'course', 'bannerfile', $_POST['datano'], $_bannerFileDir);
        }
        $bannerfile = fileUpload('banner',$_bannerFileDir, $_bannerFileAllow); 
        $sql .= ", bannerfile='".$bannerfile."'"; 
    }
    if($_POST['regcode'] != 'delete' && isset($_FILES['movie']['name']) && $_FILES['movie']['error'] == 0) {
        if($_POST['moviefile']) {
            fileDelete($_POST['moviefile'], 'course', 'moviefile', $_POST['datano'], $_movieFileDir);
        }
        $moviefile = fileUpload('movie',$_movieFileDir, $_movieFileAllow); 
        $sql .= ", moviefile='".$moviefile."'"; 
    }

    $ret = sql_query($sql.$sqlWhere) or alert('오류 : SQL오류입니다.:'.mysql_error(), './courseManage.php'); 
    switch($_POST['config']) {
        case 'add':
            goto_url('./courseManageDetail.php?add'); 
        break;
        case 'delete':
            alert('성공적으로 삭제되었습니다.', './courseManage.php'); 
        break;
        default:
            $page = 1; 
            if($_POST['datano']) {
                $res = sql_fetch("select count(*) as cnt from course where no > ".$_POST['datano']);
                $pageRet = $res[cnt]/$perPage+1;
                $page = (int)$pageRet;
            }
            goto_url('./courseManage.php?page='.$page); 
    }
}

if(isset($_GET['id'])) { //수정시 (id값이 넘어왔을때)
    $_regcode = 'modify';
    $_datano = $_GET['id']; 
    $data = getDb('course', $_datano, 'no');  
    $data['name'] = htmlspecialchars(stripslashes($data['name'])); 
    
    
    $attachfile = $data['attachfile']; 
    $bannerfile = $data['bannerfile']; 
    $moviefile = $data['moviefile']; 
    $bookcode = isset($data['bookcode']) ? $data['bookcode'] : NULL; 
    if($bookcode) {
        $_bookdata = getDb('book', $bookcode, 'no'); 
        $cate1 = $_bookdata['cate1'];
        $cate2 = $_bookdata['cate2'];
        $cate3 = $_bookdata['cate3'];
        $cate4 = $bookcode;
    }

    foreach($daysArray as $key => $v) {
        if($data[$key] == '1') {
            $weekArray[] = $v; 
        }
    }
    if(!$data['no']) {
        alert('자료가 존재하지 않습니다.');
    }
    $tpl->assign('data', $data);
}
        $res = mysql_query("SELECT mb_no, mb_name FROM g4_member WHERE mb_division='강사'" );
        $teacherData = array();
        while($teachertemp = mysql_fetch_assoc($res)) {
            $teacherData[$teachertemp['mb_no']] = $teachertemp['mb_name'];
        }

    $initialTeacher = isset($data['teacher'])? $data['teacher'] : null;
    $_teachers = _makeOptionList($teacherData, $initialTeacher);

$tpl->assign('weekArray', implode(',',$weekArray)); 
$tpl->assign('regcode', $_regcode); 
require_once ('./admin.head.php');

$tpl->define('basic',"courseDetail.html");
$tpl->print_('basic');

require_once('inc/book_category.php');
require_once('admin.foot.php');
